﻿<%@ WebHandler Language="C#" Class="UserGrantAuthorization" %>

using System;
using System.IO;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Collections;
using ReportBusiness;

/**
 * Description: MES报表用户授权
 * Copyright (c) : 通力凯顿（北京）系统集成有限公司
 * Writer:zhunan
 * Date:2022.12.6
 **/

public class UserGrantAuthorization : IHttpHandler
{
    private uMESReportOracleDAL dal = new uMESReportOracleDAL();
    public bool IsReusable { get { return false; } }
    public void ProcessRequest(HttpContext context)
    {
        string requestjson = "";
        using (StreamReader reader = new StreamReader(context.Request.InputStream)) { requestjson = reader.ReadToEnd(); }
        JObject jObject = JsonConvert.DeserializeObject(requestjson) as JObject;
        if (jObject["type"] != null)
        {
            try
            {
                Result r = new Result();
                context.Response.ContentType = "text/json";
                string type = jObject["type"].ToString();
                switch (type)
                {
                    case "isSuperAdmin":
                        r = isSuperAdmin(jObject);//查询当前用户是否信息中心管理员
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "getData":
                        r = getData(jObject);//查询
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "checkSelectPageValid":
                        r = checkSelectPageValid(jObject);//添加前校验
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "addItem":
                        r = addItem(jObject);//添加
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "deleteItem":
                        r = deleteItem(jObject);//删除
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "getFactoryUsers":
                        r = getFactoryUsers(jObject);//查询分厂人员
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "addItemUsers":
                        r = addItemUsers(jObject);//添加角色人员
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "getItemGrantedUsers":
                        r = getItemGrantedUsers(jObject);//查询已授权人员
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "removeItemUsers":
                        r = removeItemUsers(jObject);//移除角色人员
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    default:
                        break;
                }
            }
            catch (Exception e)
            {
                Result r = new Result();
                r.data = null;
                r.meta = new Result.Meta(500, e.Message);
                r.total = 0;
                context.Response.ContentType = "text/json";
                context.Response.Write(JsonConvert.SerializeObject(r));
            }
        }
    }

    //查询当前用户是否信息中心管理员
    Result isSuperAdmin(JObject jObject)
    {
        string sql = @"SELECT e.employeename,e.fullname FROM employee e WHERE e.employeename IN ('69400364','59100621', '50102249') AND e.employeeid = '{0}'";//寇延婷、梅东
        sql = string.Format(sql, jObject["employeeid"].ToString());
        DataTable dtWhiteList = dal.GetDataTable(sql);
        Result r = new Result();
        r.data = null;
        r.total = Convert.ToInt32(dtWhiteList.Rows.Count);
        r.meta = new Result.Meta(200, "查询成功");
        return r;
    }

    //查询
    Result getData(JObject jObject)
    {
        string sql = @"
SELECT e.fullname,e.employeename,mt.pagename reportpagename,t.reportpageid,t.create_date,mt.pageurl,mt.pagetype
FROM mes_report_auth t
LEFT JOIN mes_reportpage mt ON mt.pageid = t.reportpageid
LEFT JOIN employee e ON e.employeeid = t.create_emp";
        if (jObject["reportpagename"] != null && jObject["reportpagename"].ToString() != "")
        {
            sql += string.Format(" WHERE mt.pagename = '{0}'", jObject["reportpagename"].ToString());
        }
        DataTable dt = dal.GetDataTable(sql);
        foreach (DataColumn col in dt.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        Result r = new Result();
        r.data = dt;
        r.total = Convert.ToInt32(dt.Rows.Count);
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    //添加前校验
    Result checkSelectPageValid(JObject jObject)
    {
        string sql = @"
SELECT mt.pageid,DECODE(t.reportpageid,NULL,'未添加','已添加') status
FROM mes_reportpage mt 
LEFT JOIN mes_report_auth t ON t.reportpageid = mt.pageid
WHERE mt.pagename = '{0}'";
        sql = string.Format(sql, jObject["reportpagename"].ToString().Trim());
        DataTable dt = dal.GetDataTable(sql);
        foreach (DataColumn col in dt.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }

        Result r = new Result();
        r.data = dt;
        r.total = Convert.ToInt32(dt.Rows.Count);
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    //新增
    Result addItem(JObject jObject)
    {
        string sql = "INSERT INTO mes_report_auth(reportpageid,create_emp,create_date) VALUES('{0}','{1}',SYSDATE)";
        sql = string.Format(sql, jObject["reportpageid"].ToString(), jObject["employeeid"].ToString());
        int result = dal.ExecuteSql(sql);
        Result r = new Result();
        r.data = null;
        r.total = Convert.ToInt32(result);
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    //删除
    Result deleteItem(JObject jObject)
    {
        Result r = new Result();
        ArrayList sqlList = new ArrayList();
        JArray selectData = JArray.Parse(jObject["items"].ToString());
        for (int i = 0; i < selectData.Count; i++)
        {
            sqlList.Add(string.Format("DELETE mes_report_auth t WHERE t.reportpageid = '{0}'", selectData[i]["reportpageid"].ToString()));
            sqlList.Add(string.Format("DELETE mes_report_auth_users t WHERE t.reportpageid = '{0}'", selectData[i]["reportpageid"].ToString()));
        }

        try
        {
            dal.ExecuteSqlTran(sqlList);
            r.data = null;
            r.total = Convert.ToInt32(selectData.Count);
            r.meta = new Result.Meta(200, "删除成功");
            return r;
        }
        catch (Exception e)
        {
            r.data = null;
            r.total = Convert.ToInt32(0);
            r.meta = new Result.Meta(500, e.Message);
            return r;
        }
    }

    //查询分厂人员
    Result getFactoryUsers(JObject jObject)
    {
        string sql = @"
SELECT e.employeename,e.employeeid,e.fullname,CASE WHEN t.reportpageid IS NOT NULL THEN 'true' ELSE 'false' END disabled
FROM employee e
LEFT JOIN sessionvalues sv ON sv.employeeid = e.employeeid
LEFT JOIN factory f ON f.factoryid = sv.factoryid
LEFT JOIN Userattribute u ON u.parentid = f.factoryid AND u.userattributename = '分厂代码'
LEFT JOIN mes_report_auth_users t ON t.employeeid = e.employeeid AND t.reportpageid = '{0}'
WHERE 1=1 ";
        if (jObject["factoryid"].ToString() != "未指定部门")
        {
            sql += string.Format(" AND f.factoryid = '{0}'", jObject["factoryid"].ToString());
        }
        else
        {
            sql += " AND f.factoryid IS NULL";
        }

        sql = string.Format(sql, jObject["reportpageid"].ToString());
        DataTable dt = dal.GetDataTable(sql);
        foreach (DataColumn col in dt.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        Result r = new Result();
        r.data = dt;
        r.total = Convert.ToInt32(dt.Rows.Count);
        r.meta = new Result.Meta(200, "请求成功!");
        return r;
    }

    //添加用户角色
    Result addItemUsers(JObject jObject)
    {
        Result r = new Result();
        ArrayList sqlList = new ArrayList();
        JArray selectData = JArray.Parse(jObject["willBeGrantUsers"].ToString());
        string reportpageid = jObject["reportpageid"].ToString();
        for (int i = 0; i < selectData.Count; i++)
        {
            sqlList.Add(string.Format("INSERT INTO mes_report_auth_users(reportpageid,employeeid) VALUES('{0}','{1}')", reportpageid, selectData[i].ToString()));
        }

        try
        {
            dal.ExecuteSqlTran(sqlList);
            r.data = null;
            r.total = Convert.ToInt32(selectData.Count);
            r.meta = new Result.Meta(200, "添加成功");
            return r;
        }
        catch (Exception e)
        {
            r.data = null;
            r.total = Convert.ToInt32(0);
            r.meta = new Result.Meta(500, e.Message);
            return r;
        }
    }

    //查询已授权人员
    Result getItemGrantedUsers(JObject jObject)
    {
        string sql = @"
SELECT e.employeeid,e.employeename,e.fullname
FROM mes_report_auth_users t 
LEFT JOIN employee e ON e.employeeid = t.employeeid
WHERE t.reportpageid = '{0}'";
        sql = string.Format(sql, jObject["reportpageid"].ToString());
        DataTable dt = dal.GetDataTable(sql);
        foreach (DataColumn col in dt.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        Result r = new Result();
        r.data = dt;
        r.total = Convert.ToInt32(dt.Rows.Count);
        r.meta = new Result.Meta(200, "请求成功!");
        return r;
    }

    //移除角色用户
    Result removeItemUsers(JObject jObject)
    {
        Result r = new Result();
        ArrayList sqlList = new ArrayList();
        JArray selectData = JArray.Parse(jObject["willBeUnGrantUsers"].ToString());
        string reportpageid = jObject["reportpageid"].ToString();
        for (int i = 0; i < selectData.Count; i++)
        {
            sqlList.Add(string.Format("DELETE mes_report_auth_users t WHERE t.reportpageid = '{0}' AND t.employeeid = '{1}'", reportpageid, selectData[i].ToString()));
        }

        try
        {
            dal.ExecuteSqlTran(sqlList);
            r.data = null;
            r.total = Convert.ToInt32(selectData.Count);
            r.meta = new Result.Meta(200, "移除成功");
            return r;
        }
        catch (Exception e)
        {
            r.data = null;
            r.total = Convert.ToInt32(0);
            r.meta = new Result.Meta(500, e.Message);
            return r;
        }
    }
}